package com.example.component.view

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.component.R
import kotlin.random.Random

class ViewActivity : AppCompatActivity() {
    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_view)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        initViews()
    }

    private fun initViews() {
        /**
         * view.post
         */
        val textView = findViewById<TextView>(R.id.size)
        textView.post {
            val width = textView.width
            val height = textView.height
            textView.text = "View dimensions: width=$width, height=$height"
        }

        /**
         * view.viewTreeObserver
         */
        textView.viewTreeObserver.addOnGlobalLayoutListener(
            object : android.view.ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    // This method is called when the layout of the view has changed
                    val width = textView.width
                    val height = textView.height
                    Log.d(TAG, "View dimensions: width=$width, height=$height")
                    // Remove the listener to prevent multiple calls
                    textView.viewTreeObserver.removeOnGlobalLayoutListener(this)
                }
            }
        )

        val luckyWheel = findViewById<LuckyWheelView>(R.id.luckyWheel)
        val startBtn = findViewById<Button>(R.id.startBtn)
        startBtn.setOnClickListener {
            val randomIndex = Random.nextInt(6)
            luckyWheel.startSpin(randomIndex) // Assuming 6 items in the wheel
        }

    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) {
            // This is called when the window gains focus
            val view = findViewById<TextView>(R.id.size)
            val width = view.width
            val height = view.height
            Log.d(TAG, "Window focus changed: width=$width, height=$height")
        }
    }

    companion object {
        private const val TAG = "ViewActivity"
    }
}